package cn.com.cfae.iras.doc.analyze.parse;

import cn.com.cfae.iras.doc.analyze.keys.ExtractMethod;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import cn.com.cfae.iras.doc.analyze.parse.model.table.BaseTable;
import cn.com.cfae.iras.doc.analyze.parse.model.table.MTable;
import cn.com.cfae.iras.doc.analyze.parse.model.table.TableItem;
import cn.com.cfae.iras.doc.analyze.pdf.PdfExtractor;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * PDFParser，供上层应用调用
 */
public class PdfParser {

    private static Logger logger = LoggerFactory.getLogger(PdfParser.class);

    /**
     * 解析募集说明书合规性检查业务指标
     *
     * @param pdfFile
     * @param tableType
     * @return
     */
    public DocumentModel parsePdfOutline(File pdfFile, TableType tableType) {
        long t1 = System.currentTimeMillis();
        if (!pdfFile.exists()) {
            throw new RuntimeException(String.format("文件%s不存在！", pdfFile.getAbsolutePath()));
        }
        logger.info("开始分析抽取PDF，文件：{}，表格类型：{}，......", pdfFile.getAbsolutePath(), tableType.getName());
        DocumentModel documentModel;
        PDFBaseParser pdfBaseParser = null;
        switch (tableType) {
            case M:
                pdfBaseParser = new PDFMTableParser();
                break;
            case BM:
                pdfBaseParser = new PDFMTableParser();
                break;
            case DM:
                pdfBaseParser = new PDFMTableParser();
                break;
            case BDM:
                pdfBaseParser = new PDFMTableParser();
                break;
            default:
                break;
        }
        if (pdfBaseParser == null) {
            throw new RuntimeException("未找到对应表格解析器！");
        }
        documentModel = pdfBaseParser.parse(pdfFile, tableType);
        printExtractBizModel(documentModel, analyzeTableType(pdfFile.getName()), null);
        long t2 = System.currentTimeMillis();
        logger.info("分析抽取PDF完成，文件：{}，表格类型：{}，耗时：{}毫秒。", pdfFile.getAbsolutePath(), tableType.getName(), (t2 - t1));
        return documentModel;
    }

    /**
     * 解析IAAD行业指标
     *
     * @param pdfFile
     * @param industryType
     * @return
     */
    public DocumentModel parsePdfOutline(File pdfFile, IndustryType industryType) {
        long t1 = System.currentTimeMillis();
        logger.info("开始分析抽取PDF，文件：{}，行业类型：{}，......", pdfFile.getAbsolutePath(), industryType.getName());
        DocumentModel documentModel = null;
        PDFBaseParser pdfBaseParser = null;
        switch (industryType) {
            case HD:
                pdfBaseParser = new PDFMTableParser();
                break;
            case FDC:
                pdfBaseParser = new PDFMTableParser();
                break;
            case MT:
                pdfBaseParser = new PDFMTableParser();
                break;
            case SN:
                pdfBaseParser = new PDFMTableParser();
                break;
            case GT:
                pdfBaseParser = new PDFMTableParser();
                break;
            case GSGL:
                pdfBaseParser = new PDFMTableParser();
                break;
            case CJ:
                pdfBaseParser = new PDFMTableParser();
                break;
            default:
                break;
        }
        if (pdfBaseParser == null) {
            throw new RuntimeException("未找到对应文档解析器！");
        }
        //TODO 待完善
        try {
            documentModel = pdfBaseParser.parse(pdfFile, analyzeTableType(pdfFile.getName()), industryType);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
//        printExtractBizModel(documentModel, analyzeTableType(pdfFile.getName()), industryType);
        long t2 = System.currentTimeMillis();
        logger.info("分析抽取PDF完成，文件：{}，行业类型：{}，耗时：{}毫秒。", pdfFile.getAbsolutePath(), industryType.getName(), (t2 - t1));
        return documentModel;
    }


    private void printExtractBizModel(DocumentModel documentModel, TableType tableType, IndustryType industryType) {
        if (documentModel == null) {
            return;
        }
        logger.info("分析抽取PDF完成，输出数据结构：");
        List<ChapterModel> chapterModelList = documentModel.getChapterModels();
        for (int i = 0; i < chapterModelList.size(); i++) {
            ChapterModel chapterModel = chapterModelList.get(i);
            if (chapterModel == null) {
                continue;
            }
            logger.info("打印第{}章业务模型数据......", chapterModel.getChapterId());
            Map<String, ExtractBizModel> extractBizModelMap = chapterModel.getExtractBizModelMap();
            for (Iterator<String> it = extractBizModelMap.keySet().iterator(); it.hasNext(); ) {
                String key = it.next();
                ExtractBizModel extractBizModel = extractBizModelMap.get(key);
                if (extractBizModel == null) {
                    continue;
                }
                logger.info("打印第{}章业务模型数据，当前输出业务模型：{}。", chapterModel.getChapterId(), extractBizModel.getModelName());
                ExtractMethod extractMethod = extractBizModel.getExtractMethods()[0];
                try {
                    switch (extractMethod) {
                        case KV:
                            for (ExtractItem extractItem : extractBizModel.getExtractItemList()) {
                                if (extractItem.getKey() != null) {
                                    logger.info("打印第{}章业务模型数据，ExtractItem:{},key:{}.", chapterModel.getChapterId(), extractItem.getItemName(), extractItem.getKey().getTextLayout().getText());
                                }
                                if (extractItem.getValue() != null) {
                                    logger.info("打印第{}章业务模型数据，ExtractItem:{},value:{}.", chapterModel.getChapterId(), extractItem.getItemName(), extractItem.getValue().getTextLayout().getText());
                                }
                            }
                            break;
                        case TABLE:
                            if (!extractBizModel.getTables().isEmpty()) {
                                logger.info("打印第{}章业务模型数据，业务模型：{}，数据内容：{}。", chapterModel.getChapterId(), extractBizModel.getModelName(), extractBizModel.getTables());
                            } else {
                                logger.info("打印第{}章业务模型数据，数据内容为空！！！", chapterModel.getChapterId());
                            }
                            break;
                        case TABLE_2:
                            if (!extractBizModel.getTables2().isEmpty()) {
                                logger.info("打印第{}章业务模型数据，业务模型：{}，数据内容：{}。", chapterModel.getChapterId(), extractBizModel.getModelName(), extractBizModel.getTables2());
                            } else {
                                logger.info("打印第{}章业务模型数据，数据内容为空！！！", extractBizModel.getModelName());
                            }
                            break;
                        case TABLE_3:
                            if (!extractBizModel.getTables3().isEmpty()) {
                                logger.info("打印第{}章业务模型数据，业务模型：{}，数据内容：{}。", chapterModel.getChapterId(), extractBizModel.getModelName(), extractBizModel.getTables3());
                            } else {
                                logger.info("打印第{}章业务模型数据，数据内为空！！！", extractBizModel.getModelName());
                            }
                            break;
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            logger.info("打印第{}章业务模型数据完成。", chapterModel.getChapterId());
        }
    }

    private TableType analyzeTableType(String fileName) {
        if (fileName.contains("定向")) {
            return TableType.DM;
        } else {
            return TableType.M;
        }
    }
}